package com.citybox.shared.utils.aliyun;


import com.aliyun.credentials.models.Config;
import com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationRequest;
import com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.citybox.shared.config.ALiYunConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ALiYunUtils {

    private final ALiYunConfig aliYunConfig;

    public ALiYunUtils(ALiYunConfig aliYunConfig){
        this.aliYunConfig = aliYunConfig;
    }

    /**
     * 创建号码认证服务客户端（直接配置AK方式）
     */
    public com.aliyun.dytnsapi20200217.Client createClient(ALiYunConfig aliYunConfig) throws Exception {
        // 参数校验
        if (aliYunConfig.getAccessKeyId() == null || aliYunConfig.getAccessKeySecret() == null) {
            throw new IllegalArgumentException("阿里云AccessKey未配置");
        }

        // 配置凭据
        Config credentialConfig = new Config()
                .setType(aliYunConfig.getType())
                .setAccessKeyId(aliYunConfig.getAccessKeyId())
                .setAccessKeySecret(aliYunConfig.getAccessKeySecret());

        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client(credentialConfig);

        // 配置客户端
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential)
                .setEndpoint(aliYunConfig.getEndpoint())
                .setRegionId(aliYunConfig.getRegionId())
                .setConnectTimeout(10000)
                .setReadTimeout(10000);

        return new com.aliyun.dytnsapi20200217.Client(config);
    }

    /**
     * 使用环境变量创建客户端
     */
    public com.aliyun.dytnsapi20200217.Client createClientWithEnv() throws Exception {
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();

        if (accessKeyId == null || accessKeySecret == null) {
            throw new IllegalArgumentException("请设置环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        }

        return createClient(aliYunConfig);
    }

    /**
     * 身份证二要素验证
     */
    public Map<String, Object> realNameAuth(String name, String idNo) throws Exception {
        Map<String, Object> result = new HashMap<>();

        try {
            com.aliyun.dytnsapi20200217.Client client = createClientWithEnv();

            CertNoTwoElementVerificationRequest request = new CertNoTwoElementVerificationRequest()
                    .setAuthCode(aliYunConfig.getAuthCode())
                    .setCertName(name)
                    .setCertNo(idNo);

            RuntimeOptions runtime = new RuntimeOptions();

            CertNoTwoElementVerificationResponse response = client.certNoTwoElementVerificationWithOptions(request, runtime);

            if (response != null && response.getBody() != null) {
                // 解析响应
                String resultCode = response.getBody().getCode();
                String resultMessage = response.getBody().getMessage();
                String requestId = response.getBody().getRequestId();
                // 构建返回结果
                result.put("success", true);
                result.put("code", resultCode);
                result.put("message", resultMessage);
                result.put("requestId", requestId);
                result.put("timestamp", System.currentTimeMillis());
                //0不一致，1一致，2查无此人
                result.put("passed", response.getBody().getData().getIsConsistent());
                log.info(String.format("认证结果: code=%s, message=%s", resultCode, resultMessage));
            } else {
                result.put("success", false);
                result.put("code", "EMPTY_RESPONSE");
                result.put("message", "API响应为空");
                log.error("API响应为空");
            }
        } catch (Exception e) {
            log.error("认证失败:{} ", e.getMessage());
            result.put("success", false);
            result.put("code", "SYSTEM_ERROR");
            result.put("message", "认证失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        return result;
    }
}